#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import base64
import time
from datetime import datetime
from ones_config import ONES_CONFIG

def decode_jwt_payload(token):
    """解码JWT token的payload部分"""
    try:
        # JWT格式: header.payload.signature
        parts = token.split('.')
        if len(parts) != 3:
            return None, "Invalid JWT format"
        
        # 解码payload (第二部分)
        payload = parts[1]
        
        # 添加填充以防base64解码错误
        missing_padding = len(payload) % 4
        if missing_padding:
            payload += '=' * (4 - missing_padding)
        
        decoded_bytes = base64.urlsafe_b64decode(payload)
        payload_data = json.loads(decoded_bytes)
        
        return payload_data, None
        
    except Exception as e:
        return None, str(e)

def check_token_validity():
    """检查token有效性"""
    token = ONES_CONFIG["auth_token"]
    
    print("🔍 JWT Token 分析")
    print(f"Token长度: {len(token)}")
    print(f"Token前50字符: {token[:50]}...")
    
    payload, error = decode_jwt_payload(token)
    
    if error:
        print(f"❌ Token解析失败: {error}")
        return
    
    print(f"\n✅ Token解析成功")
    print(f"完整Payload: {json.dumps(payload, indent=2, ensure_ascii=False)}")
    
    # 检查关键字段
    current_time = int(time.time())
    
    if 'exp' in payload:
        exp_time = payload['exp']
        exp_datetime = datetime.fromtimestamp(exp_time)
        is_expired = current_time > exp_time
        
        print(f"\n⏰ 时间信息:")
        print(f"当前时间: {datetime.fromtimestamp(current_time)} (时间戳: {current_time})")
        print(f"过期时间: {exp_datetime} (时间戳: {exp_time})")
        print(f"是否过期: {'❌ 是' if is_expired else '✅ 否'}")
        
        if is_expired:
            days_expired = (current_time - exp_time) / 86400
            print(f"过期天数: {days_expired:.1f} 天")
        else:
            days_left = (exp_time - current_time) / 86400
            print(f"剩余天数: {days_left:.1f} 天")
    
    if 'iat' in payload:
        iat_time = payload['iat']
        iat_datetime = datetime.fromtimestamp(iat_time)
        print(f"签发时间: {iat_datetime} (时间戳: {iat_time})")
    
    if 'login_time' in payload:
        login_time = payload['login_time'] / 1000  # 看起来是毫秒
        login_datetime = datetime.fromtimestamp(login_time)
        print(f"登录时间: {login_datetime}")
    
    # 检查其他重要字段
    print(f"\n🔑 认证信息:")
    if 'org_user_uuid' in payload:
        print(f"组织用户UUID: {payload['org_user_uuid']}")
    if 'org_uuid' in payload:
        print(f"组织UUID: {payload['org_uuid']}")
    if 'scopes' in payload:
        print(f"权限范围: {payload['scopes']}")
    
    return not is_expired if 'exp' in payload else None

def test_direct_login():
    """测试直接登录"""
    print(f"\n{'='*60}")
    print("🔑 测试直接登录")
    
    import requests
    
    login_url = "https://ones.cn/api/project/auth/login"
    
    # 这里需要实际的密码
    payload = {
        "email": ONES_CONFIG["email"],
        "password": ""  # 需要填入实际密码
    }
    
    if not payload["password"]:
        print("❌ 需要配置实际密码才能测试登录")
        return
    
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "OnesAPITester/1.0",
        "Referer": "https://ones.cn/"
    }
    
    try:
        response = requests.post(login_url, json=payload, headers=headers, timeout=30)
        
        print(f"登录URL: {login_url}")
        print(f"状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            data = response.json()
            print(f"✅ 登录成功")
            print(f"新Token: {data.get('user', {}).get('token', 'N/A')[:50]}...")
        else:
            print(f"❌ 登录失败: {response.text}")
            
    except Exception as e:
        print(f"❌ 登录异常: {str(e)}")

if __name__ == "__main__":
    is_valid = check_token_validity()
    test_direct_login() 